package com.tnl.hunter.webchat.controller;

import com.biz.hunter.dao.*;
import com.biz.hunter.db.entity.*;
import com.biz.system.config.WebchatServiceConstant;
import com.biz.wechat.annotation.OAuthRequired;
import com.biz.wechat.util.DateUtil;
import com.biz.wechat.util.RadomUtils;
import com.biz.wechat.util.SignUtil;
import com.jfinal.weixin.sdk.api.ApiResult;
import com.jfinal.weixin.sdk.api.TemplateData;
import com.jfinal.weixin.sdk.api.TemplateMsgApi;
import com.tnl.hunter.webchat.common.MsgService;
import com.tnl.hunter.webchat.utils.DateUtils;
import com.tnl.hunter.webchat.utils.SMSService;
import com.tnl.hunter.webchat.utils.WxaTemplateUtil;
import net.coobird.thumbnailator.Thumbnails;
import org.apache.commons.io.FilenameUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class EmployerController {

	private static final Logger logger = LoggerFactory
			.getLogger(EmployerController.class);

	@Autowired
	private WXUserDAO userDAO;
	@Autowired
	private DomainDAO domainDAO;
	@Autowired
	private CompanyDAO companyDAO;
	@Autowired
	private CityDAO cityDAO;
	@Autowired
	private JobTitleDAO jobtitleDAO;
	@Autowired
	private TempCompanyDAO tempCompanyDAO;
	@Autowired
	private EmployerDAO employerDAO;
	@Autowired
	private RecommendRecordDAO recommendRecordDAO;
	@Autowired
	private SysConfigRepo sysConfigService;
	@Autowired
	private JobDAO jobDAO;
	
	@Autowired
	private EmployeeDAO employeeDAO;

	@Autowired
	private PersonDAO personDAO;

	@Autowired
	private RecommendDAO recommendDAO;
	@Autowired
	private InterViewDAO interviewDAO;

	@Autowired
	private MsgService msgService;

	// =================菜单入口 -- HR认证页面
	@OAuthRequired
	@RequestMapping(value = "wechat/employer/main.page", method = RequestMethod.GET)
	public String register(HttpServletRequest request, Model model) throws UnsupportedEncodingException {

		HttpSession session = request.getSession();
		String openid = (String) session.getAttribute("OpenId");
//		openid = "o852IsxjLjGA0kmPlF0bQ2suht0Y";
		logger.debug("openid is " + openid);
		if (!StringUtils.hasText(openid)) {
			logger.info("empty openid ,wexin browser is needed.");
			return "wechat/headhunter/errorpage";
		}
		UserInfo user = userDAO.getByOpenId(openid);
		if (user == null) {
			logger.info("the openid " + openid + " is not subscribed");
			return "wechat/headhunter/errorpage";
		}

		Employer employer = employerDAO.getByOpenId(openid);

		
		String ticket =sysConfigService.getJsTicket();
		String url = request.getRequestURL().toString();
		if (!StringUtils.isEmpty(request.getQueryString())) {
			url = url + "?" + request.getQueryString();
		}
		Map<String, String> jsconfig = SignUtil.getJSSignature(ticket, url);

		jsConfig config = new jsConfig();


		config.setAppid(WebchatServiceConstant.APPID);
		config.setCurrenttimestamp(jsconfig.get("timestamp"));
		config.setNonceStr(jsconfig.get("nonceStr"));
		config.setSignatureStr(jsconfig.get("signature"));
		model.addAttribute("config", config);

		logger.debug("request url is " + url);
		logger.debug("js api ticket is " + ticket);
		logger.debug("signature  is " + jsconfig.get("signature"));
		logger.debug("nonceStr  is " + jsconfig.get("nonceStr"));
		logger.debug("timestamp  is " + jsconfig.get("timestamp"));
		// 需要注册绑定
		if (employer == null) {
			employer = new Employer();
			employer.setOpenid(openid);
			model.addAttribute("employer", employer);
			return "wechat/headhunter/hr/validateEmail";
		}

		if (employer.getState().equals("generated")) {
			// 生成验证码后，
			return "wechat/headhunter/hr/validateEmail";
		}
		if (employer.getState().equals("binded")) {
			// 邮箱绑定,继续填写profile
			return toEditEmployer(request, employer.getId(), model);
		}
		int companyId = employer.getCompanyId();
		String companyname = employer.getCompanyName();

		// 注册完成的
//		int binded = employer.getBinded();

		// if(companyId <= 0 && !StringUtils.hasText(companyname)) {
		// // 没有输入完公司信息，需要继续
		// List<Company> companies = companyDAO.getALL();
		// model.addAttribute("companies", companies);
		// model.addAttribute("employer", employer);
		// return "wechat/headhunter/hr/hrxinxi21";
		// }
		List<Domain> domains = domainDAO.getAllSubDomain();
		model.addAttribute("domains", domains);
//		// 公司未认证的
//		if (companyId < 1) { 这种判断不对
//			// 未绑定，用tempCompany
//			Company company = tempCompanyDAO.getByName(companyname);
//			model.addAttribute("company", company);
//		}
		Company companyTemp = tempCompanyDAO.getByName(companyname);
		if (companyTemp != null) {
			model.addAttribute("company", companyTemp);
		} else {
			// 其它情况用归一化的公司名
			Company company = companyDAO.getByName(companyname);
			model.addAttribute("company", company);
		}

		model.addAttribute("employer", employer);
		return "wechat/headhunter/hr/hrxinxi";
	}

	// 创建HR信息
	@OAuthRequired
	@RequestMapping(value = "wechat/employer/create.do", method = RequestMethod.POST)
	public @ResponseBody Map<String, Object> persistentEmployer(HttpServletRequest request,
			Employer dto) {
		Map<String, Object> returnMap = new HashMap<String, Object>();

		HttpSession session = request.getSession();
		String openId = (String) session.getAttribute("OpenId");
		//openid = "o852IsxjLjGA0kmPlF0bQ2suht0Y";

		if (!StringUtils.hasText(openId)) {
			returnMap.put("errorcode", "40001");
			returnMap.put("msg", "必须在微信平台使用我们的服务");
			return returnMap;
		}
		if (dto == null) {
			returnMap.put("errorcode", "40001");
			returnMap.put("msg", "提交参数有错");
			return returnMap;
		}
		if (!StringUtils.hasText(dto.getName())) {
			returnMap.put("errorcode", "40001");
			returnMap.put("msg", "提交的数据有错");
			return returnMap;
		}
		if (!StringUtils.hasText(dto.getPhone())) {
			returnMap.put("errorcode", "40001");
			returnMap.put("msg", "提交的数据有错");
			return returnMap;
		}
		Employer employer = employerDAO.getByOpenId(openId);
		UserInfo user = userDAO.getByOpenId(openId);
		String headImg = employer != null ? employer.getHeadImgUrl() : "";
		if (user != null && StringUtils.isEmpty(headImg)) {
			headImg = user.getHeadimgurl();
		}

		String compName = dto.getCompanyName();
		Company company = companyDAO.getByName(compName);
		if (company != null) {
			dto.setCompanyId(company.getId());
		} else {
			dto.setCompanyId(-1);
		}

		int empId = -1;
		if (employer == null) {
			// 新创建employer
			// dto.setOpenid(openId);
			// dto.setHeadImageUrl(headImg);
			// dto.setBinded(-1);
			// Date now = new Date();
			// dto.setCreateDate(now.getTime());
			// dto.setActive(Person.activate);
			// empId = employerDAO.save(dto);
			// dto.setId(empId);
			// if(empId > 0) {
			// logger.info("successfully saved the hunter " + empId);
			// returnMap.put("errorcode", "0");
			// returnMap.put("msg", "成功创建了HR信息");
			// returnMap.put("data", dto);
			// } else {
			logger.error("failed to save the hunter " + dto);
			returnMap.put("errorcode", "50001");
			returnMap.put("msg", "创建HR信息失败，请联系管理员");
			// }
			return returnMap;
		} else {
			// 这个是编辑，编辑结束后，不允许编辑公司信息
			employer.setName(dto.getName());
			employer.setHeadImgUrl(headImg);
			// employer.setAge(dto.getAge());
			// employer.setWorkage(dto.getWorkage());
			employer.setTelephone(dto.getTelephone());
			employer.setPhone(dto.getPhone());
			employer.setEmail(dto.getEmail());
			employer.setEnglishname(dto.getEnglishname());
			employer.setCompanyName(dto.getCompanyName());
			employer.setRoleName(dto.getRoleName());
			employer.setCompanyId(dto.getCompanyId());
			employer.setBinded(-1);
			employer.setState("completed");
			employer.setActive(Person.activate);
			Date now = new Date();
			employer.setCreateDate(now.getTime());
			empId = employerDAO.update(employer);
			dto.setId(employer.getId());
			if (empId > 0) {
				if (dto.getCompanyId() == -1) {
					returnMap.put("errorcode", "0");
					returnMap.put("msg", "成功保存HR信息,请继续编辑公司信息");

					returnMap.put("data", dto);

				} else {
					returnMap.put("errorcode", "1");
					returnMap.put("msg", "成功保存HR信息");
					returnMap.put("data", dto);
				}
				String content = String.format("有新的HR(%s) 更新了信息，请及时验证处理！", dto.getName() );

				try {
//					msgService.toSendMsgToService(content);
				} catch (Exception e) {
					logger.error("发送短信失败:{}", e.getMessage());
				}
			} else {
				logger.error("failed to save the hunter " + dto);
				returnMap.put("errorcode", "50001");
				returnMap.put("msg", "更新HR信息出错");
			}

			return returnMap;
		}
	}

	// 绑定邮箱orPhone
	@OAuthRequired
	@RequestMapping(value = "/wechat/employer/bindeEmail.do", method = RequestMethod.POST)
	public @ResponseBody
	Map<String, Object> bindedEmail(HttpServletRequest request, ModelMap model,
			Employer dto) {
		Map<String, Object> returnMap = new HashMap<String, Object>();

		HttpSession session = request.getSession();

		String openId = (String) session.getAttribute("OpenId");
		//openid = "o852IsxjLjGA0kmPlF0bQ2suht0Y";
		if (!StringUtils.hasText(openId)) {
			returnMap.put("errorcode", "40001");
			returnMap.put("msg", "必须在微信平台使用我们的服务");

			return returnMap;
		}
		if (dto == null || dto.getSecureCode() == null) {// || dto.getPhone() ==
															// null
			returnMap.put("errorcode", "40001");
			returnMap.put("msg", "提交参数有错");
			return returnMap;
		}

		UserInfo user = userDAO.getByOpenId(openId);
		if (user == null) {
			logger.info("the openid " + openId + " is not subscribed");

		}
		String email = dto.getPhone();//update by adela 20191120 临时修改为手机号注册 
		logger.info("bindeEmail...emailphone="+email);
		Employer hr = employerDAO.findByOpenIdandPhone(openId, email);

		if (hr == null) {
			logger.error("failed to save the hunter " + dto);
			returnMap.put("errorcode", "40001");
			returnMap.put("msg", "系统错误,你可能没关注我们公众号");
			return returnMap;
		} else {
			// validate the secure code
			String inputCode = dto.getSecureCode();

			String secureCode = hr.getSecureCode();
//			if (secureCode == null) {
//				logger.error("failed to save the hunter " + dto);
//				returnMap.put("errorcode", "40001");
//				returnMap.put("msg", "系统错误,请重新申请验证码");
//
//				return returnMap;
//			}
			if (inputCode.equalsIgnoreCase(secureCode)) {
				// equals binded
				//hr.setEmail(dto.getEmail());
				hr.setPhone(dto.getPhone());
				hr.setState("binded");
				hr.setHeadImgUrl(user.getHeadimgurl());
				logger.info("update hunter " + hr);
				long hrId = employerDAO.updateBindedPhone(hr);

				if (hrId >= 0) {
					logger.info("successfully updated the HR " + hrId);
					returnMap.put("errorcode", "0");
					returnMap.put("msg", "成功保存HR信息");
					returnMap.put("data", hr);
				} else {
					logger.error("failed to save the hunter " + dto);
					returnMap.put("errorcode", "50001");
					returnMap.put("msg", "验证失败,注册信息有误");
				}
				return returnMap;
			}
			// not equals return
			logger.error("secureCode is not correct： " + dto.getSecureCode());
			returnMap.put("errorcode", "40001");
			returnMap.put("msg", "创建HR信息失败，请填写正确的验证码");
			return returnMap;
		}
	}
	

	// 创建HR信息，验证并绑定邮箱
	@OAuthRequired
	@RequestMapping(value = "wechat/employer/updateProfile.do", method = RequestMethod.POST)
	public @ResponseBody
	Map<String, Object> updateProfile(HttpServletRequest request, Employer dto) {
		Map<String, Object> returnMap = new HashMap<String, Object>();
		HttpSession session = request.getSession();

		String openId = (String) session.getAttribute("OpenId");
		//openid = "o852IsxjLjGA0kmPlF0bQ2suht0Y";

		if (!StringUtils.hasText(openId)) {
			returnMap.put("errorcode", "40001");
			returnMap.put("msg", "必须在微信平台使用我们的服务");
			return returnMap;
		}

		if (StringUtils.isEmpty(dto.getName())) {
			returnMap.put("errorcode", "40001");
			returnMap.put("msg", "提交的数据有错");
			return returnMap;
		}
		if (!StringUtils.hasText(dto.getEmail())) {
			returnMap.put("errorcode", "40001");
			returnMap.put("msg", "提交的数据有错，Email为空");
			return returnMap;
		}
		Employer employer = employerDAO.getByOpenId(openId);

		int empId = -1;
		if (employer == null) {
			// 新创建employer
			dto.setOpenid(openId);
			dto.setBinded(-1);
			Date now = new Date();
			dto.setCreateDate(now.getTime());
			dto.setActive(Person.activate);
			empId = employerDAO.save(dto);
			dto.setId(empId);
			if (empId > 0) {
				logger.info("successfully saved the hunter " + empId);
				returnMap.put("errorcode", "0");
				returnMap.put("msg", "成功创建了HR信息");
				returnMap.put("data", dto);
			} else {
				logger.error("failed to save the hunter " + dto);
				returnMap.put("errorcode", "50001");
				returnMap.put("msg", "创建HR信息失败，请联系管理员");
			}
			return returnMap;
		} else {
			// 这个是编辑，编辑结束后，不允许编辑公司信息
			employer.setName(dto.getName());
			// employer.setAge(dto.getAge());
			// employer.setWorkage(dto.getWorkage());
			employer.setTelephone(dto.getTelephone());
			employer.setPhone(dto.getPhone());
			employer.setEmail(dto.getEmail());
			Date now = new Date();
			employer.setCreateDate(now.getTime());
			employer.setActive(Person.activate);
			logger.info("update employer " + employer);
			empId = employerDAO.update(employer);
			dto.setId(employer.getId());
			if (empId >= 0) {
				logger.info("successfully updated the hunter " + empId);
				returnMap.put("errorcode", "1");
				returnMap.put("msg", "成功保存HR信息");
				returnMap.put("data", dto);
			} else {
				logger.error("failed to save the hunter " + dto);
				returnMap.put("errorcode", "50001");
				returnMap.put("msg", "更新HR信息出错");
			}
			return returnMap;
		}
	}

	// 显示编辑HR信息页面
	@OAuthRequired
	@RequestMapping(value = "wechat/employer/toEdit.page", method = RequestMethod.GET)
	public String toEditEmployer(HttpServletRequest request, int hrId,
			Model model) {

		HttpSession session = request.getSession();
		String openId = (String) session.getAttribute("OpenId");
		//openid = "o852IsxjLjGA0kmPlF0bQ2suht0Y";
		logger.debug("openid is " + openId);
		if (!StringUtils.hasText(openId)) {
			logger.info("empty openid ,wexin browser is needed.");
			return "wechat/headhunter/errorpage";
		}
		Employer employer = employerDAO.getByOpenId(openId);
		if (employer == null) {
			return "wechat/headhunter/errorpage";
		}
		if (hrId != employer.getId()) {
			return "wechat/headhunter/errorpage";
		}
		model.addAttribute("employer", employer);
		List<Company> companies = companyDAO.getALL();
		model.addAttribute("companies", companies);
		// List<Domain> domains = domainDAO.getAllSubDomain();
		// model.addAttribute("domains", domains);

		/* */
		String ticket =sysConfigService.getJsTicket();
		logger.debug("js api ticket is " + ticket);
		String url = request.getRequestURL().toString();
		if (!StringUtils.isEmpty(request.getQueryString())) {
			url = url + "?" + request.getQueryString();
		}
		logger.debug("request url is " + url);

		Map<String, String> jsconfig = SignUtil.getJSSignature(ticket, url);

		jsConfig config = new jsConfig();
		config.setAppid(WebchatServiceConstant.APPID);
		config.setCurrenttimestamp(jsconfig.get("timestamp"));
		config.setNonceStr(jsconfig.get("nonceStr"));
		config.setSignatureStr(jsconfig.get("signature"));
		model.addAttribute("config", config);
		/* */

		return "wechat/headhunter/hr/hrxinxi1";
	}

	/*
	 * // 暂时未用到 //@OAuthRequired
	 * 
	 * @RequestMapping(value = "wechat/employer/toView.page", method =
	 * RequestMethod.GET) public String toViewEmployer(HttpServletRequest
	 * request, int hrId, int companyId, Model model) { Employer employer =
	 * employerDAO.getById(hrId); model.addAttribute("employer", employer);
	 * String companyName = employer.getCompanyName();
	 * if(StringUtils.hasText(companyName)) { Company company =
	 * tempCompanyDAO.getById(companyId); model.addAttribute("company",
	 * company); } else { Company company = companyDAO.getById(companyId);
	 * model.addAttribute("company", company);
	 * 
	 * } model.addAttribute("employer", employer); return
	 * "wechat/headhunter/hr/hrxinxi"; }
	 */

	@OAuthRequired
	@RequestMapping(value = "wechat/hunter/hr/toViewCandidate.do", method = RequestMethod.GET)
	public String toViewEmpDetail(HttpServletRequest request, Integer empid,
			Integer jobid, Integer recommendid,Integer status,ModelMap model) {
		HttpSession session = request.getSession();
		String openid = (String) session.getAttribute("OpenId");
		//openid = "o852IsxjLjGA0kmPlF0bQ2suht0Y";
		if (empid == null || empid <= 0) {
			model.addAttribute("title","温馨提示" );
			model.addAttribute("msg", "您必须指定选择哪个候选人");
			return "wechat/headhunter/msgpage";
		}
		EmployeePerson emp = this.employeeDAO.getByEpId(empid);
		if (emp == null) {
			emp = this.personDAO.getByEmpId(empid);
		}
		City city = this.cityDAO.getById(emp.getCityId());
		JobTitle job = this.jobtitleDAO.getById(emp.getRoleId());
		Recommendation recommendation=recommendDAO.getById(String.valueOf(recommendid));
		if(recommendation!=null){
			model.addAttribute("recom", recommendation);
		}
		model.addAttribute("employee", emp);
		model.addAttribute("cityName", city.getName());
		model.addAttribute("roleName", job!=null?job.getName():"");

		/* */
		String ticket =sysConfigService.getJsTicket();
		logger.debug("js api ticket is " + ticket);
		String url = request.getRequestURL().toString();
		if (!StringUtils.isEmpty(request.getQueryString())) {
			url = url + "?" + request.getQueryString();
		}
		logger.debug("request url is " + url);

		Map<String, String> jsconfig = SignUtil.getJSSignature(ticket, url);

		jsConfig config = new jsConfig();
		config.setAppid(WebchatServiceConstant.APPID);
		config.setCurrenttimestamp(jsconfig.get("timestamp"));
		config.setNonceStr(jsconfig.get("nonceStr"));
		config.setSignatureStr(jsconfig.get("signature"));
		model.addAttribute("config", config);
		/* */

		model.addAttribute("jobId", jobid);
		model.addAttribute("recommendId",recommendid);
		model.addAttribute("status", status);
		return "wechat/headhunter/hr/candidateDetail";
	}
	
	/**
	 * 修改面试者状态
	 * @param request
	 * @param recommendId
	 * @param status
	 * @param model
	 * @return
	 */
	@OAuthRequired
	@RequestMapping(value = "wechat/hunter/hr/updateRecomStatus.do", method = RequestMethod.GET)
	public @ResponseBody Map<String, Object> updateRecomStatus(HttpServletRequest request,Integer jobId,Integer empId, Integer recommendId,Integer status,ModelMap model) {
		Map<String, Object> returnMap = new HashMap<String, Object>();
		HttpSession session = request.getSession();
		String openid = (String) session.getAttribute("OpenId");
		JobDesc jobDesc=jobDAO.getById(jobId);
		System.out.println("updateRecomStatus.do function recommendId="+recommendId);
		try {
			if(recommendId==null && jobDesc != null){
				List<Recommendation> rec = recommendDAO.getByCreateAndEmpAndJob(jobDesc.getCreatedby(),empId,jobId);
				if (rec != null && rec.size()>0) {
					returnMap.put("errorcode", "999");
					returnMap.put("msg", "已发送过沟通邀请！");

					return returnMap;
				}
				 Recommendation recommend=new Recommendation();
				 recommend.setJobId(jobId);
				 recommend.setReason("系统推荐");
				 recommend.setPlatformId(1);
				 recommend.setCreateby(jobDesc!=null?jobDesc.getCreatedby():1);
				 recommend.setStatus(1);
				 recommend.setPersonId(empId);
				 Date now = new Date();
				 recommend.setCreateDate(now.getTime());
				 int result=recommendDAO.save(recommend);
				 recommendDAO.updateStatus(status, result);
				 recommendId=Integer.valueOf(result);
				 if(result>0){
					 RecommendRecord record=new RecommendRecord();
					 record.setCreateBy(1);
					 record.setCreateTime(DateUtils.getDateTime());
					 record.setRecommendId(result);
					 record.setRemark("系统推荐你的简历");
					 record.setStatus(1);
					 recommendRecordDAO.save(record);
				 }
				}
			if(recommendId!=null){
				recommendDAO.updateStatus(status, recommendId);
				//****新增一笔记录start*****/
				RecommendRecord record=new RecommendRecord();
				record.setRecommendId(recommendId);
				record.setStatus(status);
				switch (status) {
				case 6:
					record.setRemark("职位沟通确认");
					break;
				case 5:
					record.setRemark("HR有意向并关注");
					break;
				case 3:
					record.setRemark("简历标记为不合适");
					break;
				default:
					break;
				}
				Long saveres=recommendRecordDAO.save(record);
				logger.info("insert recommendrecord return value="+saveres);
				//****新增一笔记录end***/

			}


			//推送消息查询jobid
			Recommendation recommend=recommendDAO.getById(recommendId.toString());
			JobDesc jobdesc=jobDAO.getById(recommend.getJobId());
			Company company2=companyDAO.getById(jobdesc.getCompanyId());
			Person person=personDAO.getById(recommend.getPersonId());
			if(status==6){
				//send msg 跳哪里服务号--企业沟通提醒
				String tempjsontiaos = TemplateData
						.New()
						.setTouser(person.getOpenid())
						.setTemplate_id("TLXSqMewvhnCpqJx3G0hr9WaCRNck-B6kOg8unevP6s")
						.setUrl("https://www.tiaonali.com/tnl-candidate/wechat/candidate/recommend/toView.do?jobid=" + jobdesc.getId()+"&personId="+person.getId())
						//"https://www.tiaonali.com/tnl-candidate/wechat/candidate/recommend/toView.do?jobCreateBy="+jobDesc.getCreatedby()
						//						+"&jobId="+jobdesc.getId()+"&personId="+person.getId()
						.add("first",
								"您好,您申请或者有人推荐您适合的职位， HR想和您进行详细沟通。如确认，我们将发送您的联系电话给对方；非常感谢", "#274084")
						.add("keyword1", jobdesc.getName(), "#000000")
						.add("keyword2", company2.getName(), "#F47e2d")
						.add("keyword3", "面议", "#000000")
						.add("keyword4", "以HR沟通地址为准", "#000000")
						.add("remark", "如非您本人操作请联系平台客服咨询。", "#000000")
						.build();
				System.out.println(tempjsontiaos);
				ApiResult resulttiaos = WxaTemplateUtil.sendtiaonalis(tempjsontiaos);
				logger.info("HR职位沟通确认，推送消息结果="+resulttiaos);

				Employee employee = employeeDAO.getByEmpId(empId);
				if(employee != null) {
					try {
						//短信发送给面试邀请人招聘之类的不能发送短信2018/04/13
						String url = "https://www.tiaonali.com/tnl-candidate/wechat/candidate/recommend/toView.do?jobid=" + jobdesc.getId()+"&personId="+person.getId();
						String content = employee.getName()+"，您好！您申请或有人推荐与您履历相匹配的职位，该公司HR期望与您详细沟通。如您确认，HR将获取您的电话并与您电话沟通！详情："+url;
						System.out.println("HR职位沟通确认，短信推送 手机号:"+person.getPhone()+"  内容："+content);
						SMSService.sendAskMsg(person.getPhone(),content);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}



			}else if(status==5){
				//send msg 跳哪里服务号--简历投递反馈通知
				String tempjsontiaos = TemplateData
						.New()
						.setTouser(person.getOpenid())
						.setTemplate_id("RRbziJZq4fVViT9IspPKCDteMKMgtdTndPn7zvzvcxg")
						.setUrl("https://www.tiaonali.com/tnl-candidate/wechat/candidate/recommend/toView.do?jobid=" + jobdesc.getId())
						.add("first",
								"感谢您投递我们,HR有意向并进行了关注，敬请留意。", "#274084")
						.add("keyword1", jobdesc.getName(), "#000000")
						.add("keyword2", company2.getName(), "#F47e2d")
						.add("keyword3", DateUtil.getDateTimeStr(recommend.getCreateDate()), "#000000")
						.add("remark", "", "#000000")
						.build();
				System.out.println(tempjsontiaos);
				ApiResult resulttiaos = WxaTemplateUtil.sendtiaonalis(tempjsontiaos);
				logger.info("HR有意向并关注，推送消息结果="+resulttiaos);
			}else if(status==3){
				//send msg 跳哪里服务号
				String tempjsontiaos = TemplateData
						.New()
						.setTouser(person.getOpenid())
						.setTemplate_id("RRbziJZq4fVViT9IspPKCDteMKMgtdTndPn7zvzvcxg")
						.setUrl("https://www.tiaonali.com/tnl-candidate/wechat/candidate/recommend/toView.do?jobid=" + jobdesc.getId())
						.add("first",
								"您好,非常荣幸收到您的简历，招聘方经过评估，认为您与该职位的条件不太匹配，无法进入面试阶段。", "#274084")
						.add("keyword1", jobdesc.getName(), "#000000")
						.add("keyword2", company2.getName(), "#F47e2d")
						.add("keyword3", DateUtil.getDateTimeStr(recommend.getCreateDate()), "#000000")
						.add("remark", "", "#000000")
						.build();
				System.out.println(tempjsontiaos);
				ApiResult resulttiaos = WxaTemplateUtil.sendtiaonalis(tempjsontiaos);
				logger.info("HR拒绝，推送消息结果="+resulttiaos);
			}
		} catch (Exception e) {
			logger.error("[Method  updateRecomStatus]服务出错："+e.getMessage());
		}

		returnMap.put("errorcode", "1");
		returnMap.put("msg", "已操作成功！");

		return returnMap;
	}

	/**
	 * 手机是否重复
	 * @param request
	 * @param model
	 * @param
	 * @return
	 */
	@OAuthRequired
	@RequestMapping(value = "/wechat/employer/isPhone.do", method = RequestMethod.POST)
	public @ResponseBody
	Map<String, Object> isPhone(HttpServletRequest request, ModelMap model,
			String phone) {
		Map<String, Object> returnMap = new HashMap<String, Object>();

		HttpSession session = request.getSession();

		String openId = (String) session.getAttribute("OpenId");
		//openid = "o852IsxjLjGA0kmPlF0bQ2suht0Y";
		if (!StringUtils.hasText(openId)) {
			returnMap.put("errorcode", "40001");
			returnMap.put("msg", "必须在微信平台使用我们的服务");

			return returnMap;
		}

		Employer hr = employerDAO.getByPhone(phone);

		if (hr == null) {
			logger.error("failed to save the hunter " );
			returnMap.put("errorcode", "0");
			returnMap.put("msg", "可用");
			return returnMap;
		} else {
			// not equals return
			returnMap.put("errorcode", "1");
			returnMap.put("msg", "您已有账号，请换一个试试");
			return returnMap;
		}
	}
	
	/**
	 * 邮箱是否重复
	 * @param request
	 * @param model
	 * @param
	 * @return
	 */
	@OAuthRequired
	@RequestMapping(value = "/wechat/employer/isEmail.do", method = RequestMethod.POST)
	public @ResponseBody
	Map<String, Object> isEmail(HttpServletRequest request, ModelMap model,
			String email) {
		Map<String, Object> returnMap = new HashMap<String, Object>();

		HttpSession session = request.getSession();

		String openId = (String) session.getAttribute("OpenId");
		//openid = "o852IsxjLjGA0kmPlF0bQ2suht0Y";
		if (!StringUtils.hasText(openId)) {
			returnMap.put("errorcode", "40001");
			returnMap.put("msg", "必须在微信平台使用我们的服务");

			return returnMap;
		}

		Employer hr = employerDAO.getByEmail(email);

		if (hr == null) {
			logger.error("failed to save the hunter " );
			returnMap.put("errorcode", "0");
			returnMap.put("msg", "可用");
			return returnMap;
		} else {
			// not equals return
			returnMap.put("errorcode", "1");
			returnMap.put("msg", "您已有账号，请换一个试试");
			return returnMap;
		}
	}
	

	@OAuthRequired
	@RequestMapping(value = "wechat/headhunter/hr/sendSecurityCode.do", method = RequestMethod.GET)
	public @ResponseBody Map<String, Object> genSecurityCode(HttpServletRequest request,
			String email, Model model) {
		Map<String, Object> returnMap = new HashMap<String, Object>();
		// check email/phone is generated and not expired
		// Hunter hunter = hunterDAO.getByPhone(phone);
		Employer employer = this.employerDAO.getByEmail(email);
		HttpSession session = request.getSession();
		String openid = (String) session.getAttribute("OpenId");
		//openid = "o852IsxjLjGA0kmPlF0bQ2suht0Y";

		String secureCode = null;
		if (employer != null) {

			// openid is changed?
			if (openid.equals(employer.getOpenid())) {
				// get expiredDate// regenarate and sendout
				secureCode = employer.getSecureCode();
			} else {    
				returnMap.put("msg", "您的手机号已被注册！");
				return returnMap;
			}

		} else {
			RadomUtils radom = new RadomUtils();
			// gen code
			secureCode = radom.getRadom(4);
			// save code

			employer = new Employer();
			employer.setOpenid(openid);
			//employer.setEmail(email);--原是邮箱注册20191119修正手机注册，详情查看TB upd by kiki
			employer.setPhone(email);
			employer.setSecureCode(secureCode);// 重复的
			employer.setState(Hunter.State.generated.toString());
			employer.setActive(1);
			java.util.Date timeDate = new Date();// util类型
			long time = System.currentTimeMillis();

			java.sql.Timestamp dateTime = new java.sql.Timestamp(
					time + 60 * 10 * 1000);// 10分钟有效

			employer.setExpiredTime(dateTime);
			employerDAO.saveSecureCode(employer);
		}

		try {
			// send out code
			// mailService.sendMail(email, secureCode);
			//MailService.sendMail(email, secureCode);--原是邮箱注册20191119修正手机注册，详情查看TB upd by kiki
			SMSService.sendSMS(email, secureCode);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			returnMap.put("errorcode", "50001");
			returnMap.put("msg", "手机验证码已发送!");
			return returnMap;
		}
		returnMap.put("errorcode", "0");
		returnMap.put("msg", "手机验证码已发送!");
		return returnMap;
	}

	@OAuthRequired
	@RequestMapping(value = "wechat/hr/toUploadFile.page", method = RequestMethod.GET)
	public String toUploadFile(HttpServletRequest request, Model model) {
		HttpSession session = request.getSession();
		String openid = (String) session.getAttribute("OpenId");
		//openid = "o852IsxjLjGA0kmPlF0bQ2suht0Y";

		logger.debug("openid is " + openid);
		if (!StringUtils.hasText(openid)) {
			logger.info("empty openid ,wexin browser is needed.");
			return "wechat/headhunter/errorpage";
		}

		Employer hr = employerDAO.getByOpenId(openid);
		if (hr == null) {
			return "wechat/headhunter/errorpage";
		}
		model.addAttribute("hr", hr);
		// int companyId = hunter.getCompanyId();
		// HunterCompany company = hunterCompanyDAO.getById(companyId);
		// if(company==null)
		// {
		// logger.error("the input parameter is not correct");
		// model.addAttribute("message",
		// "the input parameter about the hunter is not correct");
		// return "wechat/headhunter/errorpage";
		// }

		// JSTicket ticket = JSTicketAPI.getJsTicket(token.getAccess_token());
		String ticket = sysConfigService.getJsTicket();
		logger.debug("js api ticket is " + ticket);
		String url = request.getRequestURL().toString();
		if (!StringUtils.isEmpty(request.getQueryString())) {
			url = url + "?" + request.getQueryString();
		}
		logger.debug("request url is " + url);

		Map<String, String> jsconfig = SignUtil.getJSSignature(ticket, url);

		jsConfig config = new jsConfig();
		config.setAppid(WebchatServiceConstant.APPID);
		config.setCurrenttimestamp(jsconfig.get("timestamp"));
		config.setNonceStr(jsconfig.get("nonceStr"));
		config.setSignatureStr(jsconfig.get("signature"));

		model.addAttribute("config", config);

		// String image = company.getImageUrl();
		//
		// if(StringUtils.hasText(image))
		// {
		// return "wechat/headhunter/hunter/lietouxinxi4";
		// }
		// model.addAttribute("company", company);

		return "wechat/headhunter/hr/hrxinxi4";
	}

	@OAuthRequired
	@RequestMapping(value = "wechat/employer/uploadFile.do", method = RequestMethod.POST)
	public String uploadFile(HttpServletRequest request, MultipartFile file,
			Model model) {

		HttpSession session = request.getSession();
		String openId = (String) session.getAttribute("OpenId");
		//openid = "o852IsxjLjGA0kmPlF0bQ2suht0Y";

		if (!StringUtils.hasText(openId)) {
			logger.info("session过期,请关闭重试");
			return "wechat/headhunter/errorPage";
		}
		Employer hr = employerDAO.getByOpenId(openId);
		if (hr == null) {
			return "wechat/headhunter/errorpage";
		}
		String realPath = FileController.BASE_PATH;
		logger.debug("path is " + realPath);
		//判断文件不为空的前提下
		if (!file.isEmpty()) {
			// 创建文件
			File dir = new File(realPath);
			if (!dir.exists()) {
				dir.mkdirs();
			}
			String id = currentDate();
			String fileName = file.getOriginalFilename();
			String img = id + fileName.substring(fileName.lastIndexOf("."));// zhao.jpg
			String filePathName = realPath  + img;
			FileOutputStream imgOut;
			try {
				imgOut = new FileOutputStream(new File(dir, img));// 根据 dir 抽象路径名和
				imgOut.write(file.getBytes());// 返回一个字节数组文件的内容
				imgOut.close();
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			// String token = sysConfigService.getAccessToken();
			  // 缩略图begin
	        String thumbnailPathName = id + "small."
	                                    + FilenameUtils.getExtension(file.getOriginalFilename());
	        //added by yangkang 2016-3-30 去掉后缀中包含的.png字符串
	        if(thumbnailPathName.contains(".png")){
	            thumbnailPathName = thumbnailPathName.replace(".png", ".jpg");
	        }
	        long size = file.getSize();
	        double scale = 1.0d ;
	        if(size >= 200*1024){
	            if(size > 0){
	                scale = (200*1024f) / size  ;
	            }
	        }
	        
	        //拼接文件路劲
	        String thumbnailFilePathName = realPath+ thumbnailPathName;
	        try {
	            if(size < 200*1024){
	                Thumbnails.of(filePathName).scale(1f).outputFormat("jpg").toFile(thumbnailFilePathName);
	            }else{
	                Thumbnails.of(filePathName).scale(1f).outputQuality(scale).outputFormat("jpg").toFile(thumbnailFilePathName);
	            }
	 
	        } catch (Exception e1) {
	            return e1.getMessage();
	        }
	        //删除原文件
	        if(filePathName!=null){
	        	new File(filePathName).delete();
	        }
			logger.debug("getMedia()");
			
			hr.setImgUrl(thumbnailPathName);
			employerDAO.update(hr);
		}
		/**/
	      String ticket = sysConfigService.getJsTicket();
	      logger.debug("js api ticket is " + ticket);
	      String url = request.getRequestURL().toString();
	      if (!StringUtils.isEmpty(request.getQueryString())) {
	        url = url + "?" + request.getQueryString();
	      }
	      url=url.replace("http", "https");
	      logger.debug("request url is " + url);

	      Map<String, String> jsconfig = SignUtil.getJSSignature(ticket, url);

	      jsConfig config = new jsConfig();
	      config.setAppid(WebchatServiceConstant.APPID);
	      config.setCurrenttimestamp(jsconfig.get("timestamp"));
	      config.setNonceStr(jsconfig.get("nonceStr"));
	      config.setSignatureStr(jsconfig.get("signature"));

	      model.addAttribute("config", config);
	      //send sms Lin
			try {
				SMSService.sendCheckSMS(hr.getEmail(), "HR");
			} catch (Exception e) {
				e.printStackTrace();
			}
		      
			//send msg headoffer Lin
			String tempjsonemployer = TemplateData
					.New()
					.setTouser(WebchatServiceConstant.SENDSMSLIN)
					.setTemplate_id("POheDTxtThQUaqzoDVt__a7GaHY4GP4nt4v7HB4OCG4")
					.setUrl("https://www.headoffer.com/hrplus")
					.add("first",
							"您好，用户"+hr.getEmail()+"已经提交认证信息，请审核", "#274084")
					.add("keyword1", hr.getEmail(), "#000000")
					.add("keyword2","HR认证", "#F47e2d")
					.add("keyword3","待审核", "#000000")
					.add("keyword4",DateUtils.getDate(), "#000000")
					.add("remark", "如非您本人操作请联系平台客服咨询，点击查看详情。", "#000000")
					.build();
			System.out.println(tempjsonemployer);
			ApiResult resulthunters = TemplateMsgApi.send(tempjsonemployer);
			logger.info("headoffer review check ，send msg result="+resulthunters);
		/**/
		return "wechat/headhunter/hr/hrxinxi41";
	}

	// HR认证创建公司第一页
	@OAuthRequired
	@RequestMapping(value = "wechat/employer/toBindCompany.page", method = RequestMethod.GET)
	public String toBindCompany(HttpServletRequest request, int employerId,
			Model model) {

		HttpSession session = request.getSession();

		String openid = (String) session.getAttribute("OpenId");
		//openid = "o852IsxjLjGA0kmPlF0bQ2suht0Y";

		logger.debug("openid is " + openid);
		if (!StringUtils.hasText(openid)) {
			logger.info("empty openid ,wexin browser is needed.");
			return "wechat/headhunter/errorpage";
		}

		UserInfo user = userDAO.getByOpenId(openid);
		if (user == null) {
			logger.info("the openid " + openid + " is not subscribed");
			return "wechat/headhunter/errorpage";
		}

		Employer employer = employerDAO.getByOpenId(openid);
		if (employer == null) {
			model.addAttribute("errormsg", "系统错误, Hr用户不存在");
			return "wechat/headhunter/errorpage";
		}
		if (employer.getId() != employerId) {
			model.addAttribute("errormsg", "系统错误, Hr用户不存在");
			return "wechat/headhunter/errorpage";
		}

		model.addAttribute("employer", employer);
		int compId = employer.getCompanyId();
		Company company = companyDAO.getById(compId);
		if (company != null) {
			model.addAttribute("company", company);
		}

		List<Company> companies = companyDAO.getALL();
		model.addAttribute("companies", companies);

		/* */
	      String ticket = sysConfigService.getJsTicket();
	      logger.debug("js api ticket is " + ticket);
	      String url = request.getRequestURL().toString();
	      if (!StringUtils.isEmpty(request.getQueryString())) {
	        url = url + "?" + request.getQueryString();
	      }
	      url=url.replace("http", "https");
	      logger.debug("request url is " + url);

	      Map<String, String> jsconfig = SignUtil.getJSSignature(ticket, url);

	      jsConfig config = new jsConfig();
	      config.setAppid(WebchatServiceConstant.APPID);
	      config.setCurrenttimestamp(jsconfig.get("timestamp"));
	      config.setNonceStr(jsconfig.get("nonceStr"));
	      config.setSignatureStr(jsconfig.get("signature"));

	      model.addAttribute("config", config);
		/* */

		return "wechat/headhunter/hr/bindCompany";

	}

	@OAuthRequired
	@RequestMapping(value = "/wechat/employer/bindedCompany.do", method = RequestMethod.POST)
	public @ResponseBody
	Map<String, Object> bindedCompany(HttpServletRequest request,
			ModelMap model, Employer dto) {
		Map<String, Object> returnMap = new HashMap<String, Object>();

		HttpSession session = request.getSession();

		String openId = (String) session.getAttribute("OpenId");
		//openid = "o852IsxjLjGA0kmPlF0bQ2suht0Y";

		if (!StringUtils.hasText(openId)) {
			returnMap.put("errorcode", "40001");
			returnMap.put("msg", "必须在微信平台使用我们的服务");

			return returnMap;
		}
		if (dto == null || dto.getCompanyName() == null) {// || dto.getPhone()
															// == null
			returnMap.put("errorcode", "40001");
			returnMap.put("msg", "提交参数有错");
			return returnMap;
		}

		UserInfo user = userDAO.getByOpenId(openId);
		if (user == null) {
			logger.info("the openid " + openId + " is not subscribed");

		}
		String email = dto.getEmail();

		Employer hr = employerDAO.getByOpenId(openId);

		if (hr == null) {
			logger.error("failed to save the hunter " + dto);
			returnMap.put("errorcode", "40001");
			returnMap.put("msg", "系统错误,你可能没关注我们公众号");
			return returnMap;
		} else {
			String compName = dto.getCompanyName();
			Company company = companyDAO.getByName(compName);
			if (company != null) {
				hr.setCompanyId(dto.getCompanyId());
			} else {
				hr.setCompanyId(-1);
			}
			// hr.setCompanyId(dto.getCompanyId());
			hr.setCompanyName(dto.getCompanyName());
			hr.setRoleName(dto.getRoleName());
			hr.setEnglishname(dto.getEnglishname());

			// validate the secure code
			// hr.setEmail(dto.getEmail());
			hr.setState("completed");
			hr.setHeadImgUrl(user.getHeadimgurl());
			logger.info("update hunter " + hr);
			long hrId = employerDAO.updateCompanyInfo(hr);
			// this.companyDAO.update(com)//TODO:

			if (hrId >= 0) {
				logger.info("successfully updated the HR " + hrId);
				returnMap.put("errorcode", "0");
				returnMap.put("msg", "成功保存HR信息");
				returnMap.put("data", hr);
			} else {
				logger.error("failed to save the hr " + dto);
				returnMap.put("errorcode", "50001");
				returnMap.put("msg", "系统错误，请稍后重试");
			}
			return returnMap;
		}

	}

	@OAuthRequired
	@RequestMapping(value = "wechat/employer/confirm.page", method = RequestMethod.GET)
	public String confirmPage(HttpServletRequest request, int hrId, Model model) {

		HttpSession session = request.getSession();
		String openId = (String) session.getAttribute("OpenId");
		//openid = "o852IsxjLjGA0kmPlF0bQ2suht0Y";

		if (!StringUtils.hasText(openId)) {
			logger.info("session过期,请关闭重试");
			return "wechat/headhunter/errorPage";
		}

		// Employer employer = employerDAO.getById(hrId);
		Employer employer = employerDAO.getByOpenId(openId);
		if (employer == null) {
			// msg.setErrorcode("4001");
			logger.error("invalid input parameter about hrId");
			return "wechat/headhunter/errorpage";
		}
		if (employer.getId() != hrId) {
			logger.error("invalid input parameter about hrId");
			return "wechat/headhunter/errorpage";
		}

		UserInfo user = userDAO.getByOpenId(openId);
		if (user == null) {
			logger.info("the openid " + openId + " is not subscribed");

		}
		// 2 employer
		int compId = employer.getCompanyId();
		String compName = employer.getCompanyName();
		employer.setHeadImgUrl(user.getHeadimgurl());
		employer.setState("completed");
		employerDAO.updateCompanyInfo(employer);
		if (compId <= 0) {
			logger.error("invalid input parameter about hrId");
			return "wechat/headhunter/errorpage";
		}
		// 3 company
		Company company = null;
		company = tempCompanyDAO.getById(compId);
		if (company == null) {
			logger.error("invalid input parameter about companyname");
			return "wechat/headhunter/errorpage";
		}
		// company.setImage(resId);
		// tempCompanyDAO.update(company);

		/* */
	      String ticket = sysConfigService.getJsTicket();
	      logger.debug("js api ticket is " + ticket);
	      String url = request.getRequestURL().toString();
	      if (!StringUtils.isEmpty(request.getQueryString())) {
	        url = url + "?" + request.getQueryString();
	      }
	      url=url.replace("http", "https");
	      logger.debug("request url is " + url);

	      Map<String, String> jsconfig = SignUtil.getJSSignature(ticket, url);

	      jsConfig config = new jsConfig();
	      config.setAppid(WebchatServiceConstant.APPID);
	      config.setCurrenttimestamp(jsconfig.get("timestamp"));
	      config.setNonceStr(jsconfig.get("nonceStr"));
	      config.setSignatureStr(jsconfig.get("signature"));

	      model.addAttribute("config", config);
		/* */

		return "wechat/headhunter/hr/hrxinxi4";
	}

	// 保存推荐信息，做必要的检查
	@OAuthRequired
	@ResponseBody
	@RequestMapping(value = "wechat/headhunter/recommend/recommendInterview.do", method = RequestMethod.POST)
	public Map<String, Object> recommendAndInterview(
			HttpServletRequest request, Integer jobId, Integer empId,
			ModelMap model) {
		Map<String, Object> msg = new HashMap<String, Object>();

		HttpSession session = request.getSession();

		String openid = (String) session.getAttribute("OpenId");
		//openid = "o852IsxjLjGA0kmPlF0bQ2suht0Y";

		logger.debug("openid is " + openid);
		if (StringUtils.isEmpty(openid)) {
			logger.debug("openid is null");
			msg.put("errorcode", -1);
			msg.put("msg", "您尚未关注我们");
			return msg;
		}
		UserInfo user = userDAO.getByOpenId(openid);
		if (user == null) {
			logger.info("the openid=" + openid + " is not subscribed");
			msg.put("errorcode", -1);
			msg.put("msg", "您尚未关注我们");
			return msg;
		}
		Employer hr = this.employerDAO.getByOpenId(openid);
		if (hr == null) {
			msg.put("errorcode", -2);
			msg.put("msg", "您尚未注册我们");
			return msg;
		}

		// 检查（根据手机号码、候选人姓名）检查该人是否已经被推荐该职位
		Person candidate = personDAO.getById(empId);
		List<Recommendation> list = null;
		list = recommendDAO.getByJobAndPhone(jobId, candidate.getPhone());
		if (list.size() > 0) {
			msg.put("errorcode", -3);
			msg.put("msg", "此候选人已经被推荐给该职位");
			return msg;
		}

		Recommendation recommend = new Recommendation();
		recommend.setJobId(jobId);
		recommend.setReason("hr推荐");
		recommend.setPlatformId(2);

		recommend.setCreateby(hr.getId());
		recommend.setPersonId(empId);
		Date now = new Date();
		recommend.setCreateDate(now.getTime());

		// 创建推荐信息
		int id = recommendDAO.save(recommend);
		if (id == -1) {
			logger.error("can not create Recommendation " + candidate);
			msg.put("errorcode", -4);
			msg.put("msg", "操作出错");
			return msg;
		}

		Interview itv = new Interview();
		itv.setRecommendId(id);
		itv.setItype(5);
		itv.setStatus(1);
		// Date now = new Date();
		itv.setCreateTime(now.getTime());
		itv.setUpdateTime(new java.sql.Date(now.getTime()));
		Long interviewId = interviewDAO.save(itv);
		if (interviewId <= 0) {
			msg.put("errorcode", -2);
			msg.put("msg", "保存面试信息失败");
			return msg;
		}
		itv.setId(interviewId.intValue());
		msg.put("errorcode", 0);
		// msg.put("msg", "推荐成功");
		msg.put("msg", "邀请已发送，等待系统已批复！");
		msg.put("recommendId", id);
		return msg;
	}

	@OAuthRequired
	@RequestMapping(value = "wechat/employer/success.page", method = RequestMethod.GET)
	public String hrxinxiPage(HttpServletRequest request, Model model) {

		HttpSession session = request.getSession();
		String openId = (String) session.getAttribute("OpenId");
		//openid = "o852IsxjLjGA0kmPlF0bQ2suht0Y";

		if (!StringUtils.hasText(openId)) {
			logger.info("session过期,请关闭重试");
			return "wechat/headhunter/errorPage";
		}
		Employer employer = employerDAO.getByOpenId(openId);
		if (employer == null) {
			// msg.setErrorcode("4001");
			logger.error("invalid input parameter about hrId");
			return "wechat/headhunter/errorpage";
		}
		
	      String ticket = sysConfigService.getJsTicket();
	      logger.debug("js api ticket is " + ticket);
	      String url = request.getRequestURL().toString();
	      if (!StringUtils.isEmpty(request.getQueryString())) {
	        url = url + "?" + request.getQueryString();
	      }
	      url=url.replace("http", "https");
	      logger.debug("request url is " + url);
	
	      Map<String, String> jsconfig = SignUtil.getJSSignature(ticket, url);
	
	      jsConfig config = new jsConfig();
	      config.setAppid(WebchatServiceConstant.APPID);
	      config.setCurrenttimestamp(jsconfig.get("timestamp"));
	      config.setNonceStr(jsconfig.get("nonceStr"));
	      config.setSignatureStr(jsconfig.get("signature"));
	      
	      model.addAttribute("config", config);
		/* */
	    //send sms Lin
		try {
			SMSService.sendCheckSMS(employer.getEmail(), "HR");
		} catch (Exception e) {
			e.printStackTrace();
		}
	      
		//send msg headoffer Lin
		String tempjsonemployer = TemplateData
				.New()
				.setTouser(WebchatServiceConstant.SENDSMSLIN)
				.setTemplate_id("POheDTxtThQUaqzoDVt__a7GaHY4GP4nt4v7HB4OCG4")
				.setUrl("https://www.headoffer.com/hrplus")
				.add("first",
						"您好，用户"+employer.getEmail()+"已经提交认证信息，请审核", "#274084")
				.add("keyword1", employer.getEmail(), "#000000")
				.add("keyword2","HR认证", "#F47e2d")
				.add("keyword3","待审核", "#000000")
				.add("keyword4",DateUtils.getDate(), "#000000")
				.add("remark", "如非您本人操作请联系平台客服咨询，点击查看订单详情。", "#000000")
				.build();
		System.out.println(tempjsonemployer);
		ApiResult resulthunters = TemplateMsgApi.send(tempjsonemployer);
		logger.info("headoffer review check ，send msg result="+resulthunters);
		
	      

		return "wechat/headhunter/hr/hrxinxi41";
	}

	public static String currentDate() {
		return new SimpleDateFormat("yyyyMMddHHmmss").format(System
				.currentTimeMillis());
	}
}
